package com.cmeduSystem.common.online.script;

import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.annotations.JSConstructor;
import org.mozilla.javascript.annotations.JSFunction;

/**
 * ApiQueryBuilder的JavaScript转换器
 *
 * @author xulei
 * @date 2025-09-04
 */
public class JsQueryBuilder extends ScriptableObject {

    private final ApiQueryBuilder apiQueryBuilder;

    @Override
    public String getClassName() {
        return "ApiQueryBuilder";
    }

    @JSConstructor
    public JsQueryBuilder() {
        apiQueryBuilder = ApiQueryBuilder.create();
    }

    @JSFunction
    public JsQueryBuilder sql(String sql) {
        apiQueryBuilder.setSql(sql);
        return this;
    }

    @JSFunction
    public JsQueryBuilder addParam(Object param) {
        apiQueryBuilder.addParam(param);
        return this;
    }

    @JSFunction
    public JsQueryBuilder addParams(NativeArray params) {
        for (Object param : params) {
            apiQueryBuilder.addParam(param);
        }
        return this;
    }

    @JSFunction
    public JsQueryBuilder pageParam(JsPageParam pageParam) {
        apiQueryBuilder.setPageParam(pageParam.unwrap());
        return this;
    }

    @JSFunction
    public JsQueryBuilder relations(NativeArray jsRelations) {
        apiQueryBuilder.setRelations(jsRelations);
        return this;
    }

    @JSFunction
    public JsQueryBuilder dictRelations(NativeArray jsDictRelations) {
        apiQueryBuilder.setDictRelations(jsDictRelations);
        return this;
    }

    public ApiQueryBuilder unwrap() {
        return apiQueryBuilder;
    }

    /**
     * 将ApiQueryBuilder类转换为JavaScript构造函数
     */
    public static void convertToJsConstructor(Scriptable scope) {
        try {
            // 使用defineClass方法将ApiQueryBuilder类暴露给JavaScript
            ScriptableObject.defineClass(scope, JsQueryBuilder.class);
        } catch (Exception e) {
            throw new RuntimeException("Failed to define ApiQueryBuilder class in JavaScript: " + e.getMessage(), e);
        }
    }
}